package com.yzpass.api.product;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yzpass.api.common.FilterDTO;
import com.yzpass.api.common.OffsetPage;
import com.yzpass.api.common.Result;
import io.micrometer.common.util.StringUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class ProductService {

    @Resource
    ProductMapper productMapper;

    public Result delete(String id) {
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Product::getProductId, UUID.fromString(id));
        productMapper.delete(queryWrapper);
        return Result.success();
    }

    public Result<ProductDTO> save(ProductDTO input) {
        Product dbProduct = productMapper.selectById(input.getProductId());
        Product inputProduct = input.toProduct();

        if(dbProduct==null){
            productMapper.insert(inputProduct);
        }else{
            productMapper.updateById(inputProduct);
        }

        return view(input.getProductId());
    }

    public Result<ProductDTO> view(String id) {
        Product product = productMapper.selectById(id);
        ProductDTO dto = ProductDTO.fromProduct(product);
        return Result.success(dto);
    }

    public Result<List<ProductDTO>> list(FilterDTO input) {
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(input.getKeyword())){
            String keyword = input.getKeyword();
            queryWrapper.nested(c-> c.like(Product::getProductCode,keyword)
                    .or().like(Product::getProductName,keyword));
        }

        queryWrapper.orderByAsc(Product::getProductCode);
        OffsetPage<Product> p = new OffsetPage<>(input.getOffset(),input.getSize());
        IPage<Product> iPage =  productMapper.selectPage(p,queryWrapper);
        List<ProductDTO> list = iPage.getRecords().stream().map(ProductDTO::fromProduct).toList();
        return Result.success(list,iPage.getTotal());
    }
}
